package com.xxyy.mylive.ui.activity;

import android.content.Intent;
import android.hardware.Camera;
import android.opengl.GLSurfaceView;
import android.os.PowerManager;
import android.view.View;
import android.widget.ImageView;

import com.orhanobut.logger.Logger;
import com.qiniu.pili.droid.streaming.AVCodecType;
import com.qiniu.pili.droid.streaming.CameraStreamingSetting;
import com.qiniu.pili.droid.streaming.MediaStreamingManager;
import com.qiniu.pili.droid.streaming.StreamingProfile;
import com.qiniu.pili.droid.streaming.StreamingState;
import com.qiniu.pili.droid.streaming.StreamingStateChangedListener;
import com.qiniu.pili.droid.streaming.widget.AspectFrameLayout;
import com.xxyy.mylive.R;
import com.xxyy.mylive.ui.BaseActivity;

import org.json.JSONObject;

import java.net.URISyntaxException;

public class RecordingActivity extends BaseActivity implements StreamingStateChangedListener, View.OnClickListener {
    private AspectFrameLayout afl;
    private GLSurfaceView glSurfaceView;
    private ImageView btnSwitch, btnClose, btnShareRecord;

    private JSONObject mJSONObject;
    private MediaStreamingManager mMediaStreamingManager;
    private StreamingProfile mProfile;
    private CameraStreamingSetting mSetting;


    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_recording);
    }

    @Override
    protected void initUI() {
        afl = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl);
        glSurfaceView = (GLSurfaceView) findViewById(R.id.cameraPreview_surfaceView);

        btnClose = (ImageView) findViewById(R.id.btn_close_recording);
        btnSwitch = (ImageView) findViewById(R.id.btn_switch_camera);
        btnShareRecord = (ImageView) findViewById(R.id.btn_share_record_room);
    }

    @Override
    protected void setListener() {
        btnClose.setOnClickListener(this);
        btnSwitch.setOnClickListener(this);
        btnShareRecord.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        // 预览模式为全屏
        afl.setShowMode(AspectFrameLayout.SHOW_MODE.FULL);

        //获取推流地址
        String publishRtmpUrl = getIntent().getStringExtra("publish_rtmp");
        Logger.i("rmtp =====" + publishRtmpUrl);
        try {
//            mJSONObject = new JSONObject(streamJsonStrFromServer);
//            StreamingProfile.Stream stream = new StreamingProfile.Stream(mJSONObject);
            mProfile = new StreamingProfile();
            mProfile.setVideoQuality(StreamingProfile.VIDEO_QUALITY_HIGH1)
                    .setAudioQuality(StreamingProfile.AUDIO_QUALITY_MEDIUM2)
                    .setEncodingSizeLevel(StreamingProfile.VIDEO_ENCODING_HEIGHT_480)
                    .setEncoderRCMode(StreamingProfile.EncoderRCModes.QUALITY_PRIORITY)
                    .setPublishUrl(publishRtmpUrl);
            //.setStream(stream);  // You can invoke this before startStreaming, but not in initialization phase.

            mSetting = new CameraStreamingSetting();
            mSetting.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT)
                    .setContinuousFocusModeEnabled(true)
                    .setCameraPrvSizeLevel(CameraStreamingSetting.PREVIEW_SIZE_LEVEL.MEDIUM)
                    .setCameraPrvSizeRatio(CameraStreamingSetting.PREVIEW_SIZE_RATIO.RATIO_16_9);

            mMediaStreamingManager = new MediaStreamingManager(this, afl, glSurfaceView, AVCodecType.SW_VIDEO_WITH_SW_AUDIO_CODEC);
            mMediaStreamingManager.prepare(mSetting, mProfile);
            mMediaStreamingManager.setStreamingStateListener(this);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        //开始播放
        mMediaStreamingManager.startStreaming();

        keepScreenWake();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMediaStreamingManager.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // You must invoke pause here.
        mMediaStreamingManager.pause();
        cancelScreenWake();
    }

    /**
     * 屏幕常亮
     */
    private void keepScreenWake() {
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "record");
        wakeLock.acquire();
    }

    /**
     * 取消常亮
     */
    private void cancelScreenWake() {
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
    }

    @Override
    public void onStateChanged(StreamingState state, Object o) {
        switch (state) {
            case PREPARING:
                break;
            case READY:
                // start streaming when READY
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (mMediaStreamingManager != null) {
                            mMediaStreamingManager.startStreaming();
                        }
                    }
                }).start();
                break;
            case CONNECTING:
                break;
            case STREAMING:
                // The av packet had been sent.
                break;
            case SHUTDOWN:
                // The streaming had been finished.
                break;
            case IOERROR:
                // Network connect error.
                break;
            case SENDING_BUFFER_EMPTY:
                break;
            case SENDING_BUFFER_FULL:
                break;
            case AUDIO_RECORDING_FAIL:
                // Failed to record audio.
                break;
            case OPEN_CAMERA_FAIL:
                // Failed to open camera.
                break;
            case DISCONNECTED:
                // The socket is broken while streaming
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_close_recording:
                finish();
                break;
            case R.id.btn_switch_camera:
                //切换摄像头
                mMediaStreamingManager.switchCamera();
                break;
            case R.id.btn_share_record_room:
                //模拟分享直播间,跳转webview
                Intent intent = new Intent(RecordingActivity.this,WebActivity.class);
                String webUrl = "http://123.56.0.33/index.php?r=site%2Fabout";
                intent.putExtra("web_url",webUrl);
                startActivity(intent);
                break;
        }
    }
}
